import Mock from "mockjs";
import moment from "moment";

Mock.mock("/api/data", "get", {
  "lifeList|1-10": [
    {
      "value|+1": 1,
      label: "@name",
      "age|20-30": 23,
    },
  ],
});

Mock.mock("/api/file", "post", {
  url: "/file/123/@name"
});

Mock.mock("/api/tree", "get", {
  "tree|1-10": [
    {
      "value|+1": 1,
      label: "@name",
      "children|1-5": [
        {
          "value|+1": 1,
           label: "@name",
           "children|1-5": [
            {
              "value|+1": 1,
               label: "@name",
            }
          ]
        }
      ]
    },
  ],
});

//分页数据
const Random = Mock.Random

let originList = []
const count = 100

for(let i = 0; i < count; i++) {
    originList.push({
        id: i+1,
        name: Random.ctitle(5, 10),
        number: 'P202203' + Random.integer(1, 1000),
        time: Random.datetime(),
        email: Random.email(),
        age: Random.natural( 10, 90 ),
        desc: Random.csentence()
    })
}

Mock.mock('/api/add', 'post', (params) => {
  const body = JSON.parse(params.body);
  if(!body.id) {
    body.time = body.timeStart + " - " + body.timeEnd;
    originList.push(body); 
  } else {
    const index = originList.findIndex(e => e.id === body.id);
    originList[index] = {...body};
  }
  return {
    code: 200,
    message: 'success',
  }
});

Mock.mock('/api/delete', 'post', (params) => {
  const body = JSON.parse(params.body);
  console.log(body);
  originList = originList.filter(e => {
    const index = body.findIndex(es => es === e.id);
    return index === -1;
  })
  return {
    code: 200,
    message: 'success',
  }
});

Mock.mock('/api/page', 'post', (params) => {
    const body = JSON.parse(params.body);
    let { page, pageSize, name = "", number = "", email = "", time } = body;
    let filterList = originList.filter(e =>
       e.name.indexOf(name) !== -1 && e.number.indexOf(number) !== -1 && e.email.indexOf(email) !== -1);
    if(time) {
      filterList = originList.filter(e => 
        moment(e.time).isBetween(time[0], time[1])
      )
    }
    let total = filterList.length;
    let len = total / pageSize;
    const totalPage = Number.isInteger(len) ? len + 1 : len;
    const list = filterList.slice((page - 1) * pageSize, page * pageSize)

    return {
        code: 200,
        message: 'success',
        page,
        total,
        totalPage,
        list
    }
})